using System.Configuration;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace DZRemoteController.Rules
{
	class ConnectDisconnectRule : SayItRule
	{
		private string disconnectFile;
		private bool isConnectedNow = true;
		private byte connectEvent = 0;
		private byte disconnectEvent = 0;

 
		public override void Init(RuleElement rule)
		{
			entry = rule.Entry;
			string[] files = rule.FileName.Split(';');
			FileName = Application.StartupPath + @"\Sound\" + files[0];
			if (files.Length == 2)
				disconnectFile = Application.StartupPath + @"\Sound\" + files[1];
			else
				disconnectFile = string.Empty;

			ComPortConfigSection comSection = (ComPortConfigSection)ConfigurationManager.GetSection("comPortSection");
			SerialPortPropertiesElement prop = comSection.Options;
			connectEvent = comSection.Protocol.ConnectedEvent;
			disconnectEvent = comSection.Protocol.DisconnectedEvent;

		}

		public override bool IsActive
		{
			get { return GameController.State.IsConnectionActive; }
			set { GameController.State.IsConnectionActive = value; }
		}

		public override bool Validate(string document)
		{
			Match m = Regex.Match(document, entry);
			isConnectedNow = !m.Success;
			if (isConnectedNow)
			{
				fileName = initFileName;
				GameController.State.LastEventNo = connectEvent;
			}
			else
			{
				fileName = disconnectFile;
				GameController.State.LastEventNo = disconnectEvent;
			}
			return true;
		}

		public override void Perform()
		{
			if (IsActive && GameController.State.IsConnected)
				IsActive = false;

			if (isConnectedNow != GameController.State.IsConnected)
			{
				IsActive = true;
				GameController.State.IsConnected = isConnectedNow;
			}
			base.Perform();
			IsActive = false;
		}
	}
}